package com.shuai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuai.dao.*;
import com.shuai.model.vo.*;
import com.shuai.service.ProjectService;
import com.shuai.utils.PageUtil;
import com.shuai.utils.R;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : 帅宏-coding
 * @version : 1.0
 * @date : 2025/6/23 0023
 */
@Service
public class ProjectServiceImpl implements ProjectService {
    @Resource
    private ModuleDao moduleDao;

    @Resource
    private ProjectDao projectDao;

    @Resource
    private TaskDao taskDao;
    @Resource
    private UserDao userDao;
    @Resource
    private SubProjectDao subProjectDao;

    @Override
    public R indexData(UserVO vo) {
        Map<String, Object> indexData = new HashMap<>();
        //TODO 读取菜单
        LambdaQueryWrapper<ModuleVO> moduleWrapper = new LambdaQueryWrapper<>();
        moduleWrapper.eq(ModuleVO::getDelflag, "0");
        List<ModuleVO> allModuleList = this.moduleDao.selectList(moduleWrapper);
        //TODO 获取一级菜单
        List<ModuleVO> parentModuleList = new ArrayList<>();
        for (ModuleVO moduleVO : allModuleList) {
            if (moduleVO.getParentModuleId().equals(Integer.valueOf(0))) {
                parentModuleList.add(moduleVO);
            }
        }
        for (ModuleVO moduleVO : parentModuleList) {
            List<ModuleVO> childModuleList = getChildModuleList(moduleVO.getModuleId(), allModuleList);
            moduleVO.setChildModuleList(childModuleList);
        }
        indexData.put("moduleList", parentModuleList);
        //TODO 最近的5个项目
        List<ProjectVO> projectVOS = projectDao.projectListOfIndex();
        indexData.put("projectList", projectVOS);
        //TODO 当前登录用户的最近的5个任务
        System.out.println(vo.getUserId());
        List<TaskVO> taskVOS = this.taskDao.taskListOfUserIndex(vo);
        indexData.put("taskList", taskVOS);
        //TODO  最新添加的5个用户
        List<UserVO> userVOS = this.userDao.selectUserOfIndex();
        indexData.put("userList", userVOS);
        return R.ok(indexData);
    }

    @Override
    public R projectList(Map<String, Object> params) {
        params = PageUtil.page(params);
        Map<String, Object> res = this.projectDao.totalSize(params);

        List<ProjectVO> projectVOS = this.projectDao.projectList(params);
        //TODO 查看当前用户是否是超级管理员
        LambdaQueryWrapper<UserVO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserVO::getUserId, Integer.parseInt(params.get("userId").toString()));
        UserVO userVO = this.userDao.selectOne(lambdaQueryWrapper);
        if (userVO.getIsAdmin().equals(0)) {

            //TODO 如果当前用户不是超级管理员，那么该用户可以查看哪些项目的详情
            List<Integer> projectIds = this.projectDao.selectProjectOfUserId(params);
            if (projectIds == null || projectIds.size() == 0) {
                projectIds = new ArrayList<>();
            }
            Integer userId = Integer.parseInt(params.get("userId").toString());
            projectIds.addAll(projectVOS.stream()
                    .filter(x -> x.getManagerId().equals(userId))
                    .map(x -> x.getProjectId())
                    .collect(Collectors.toList()));
            if (projectIds.size() > 0) {
                for (int i = 0; i < projectVOS.size(); i++) {
                    isShow:
                    for (int j = 0; j < projectIds.size(); j++) {
                        if (projectVOS.get(i).getProjectId().equals(projectIds.get(j))) {
                            projectVOS.get(i).setIsShowProjectInfo(true);
                            break isShow;
                        }
                    }
                }
            }
        }
        res.put("projectList", projectVOS);
        return R.ok(res);
    }

    @Override
    public R addProject(ProjectVO vo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        vo.setIntime(sdf.format(new Date()));
        int row = this.projectDao.insert(vo);
        if (row > 0) {
            return R.ok();
        } else {
            return R.er();
        }
    }

    @Override
    public R projectInfo(Map<String, Object> params) {
        params = PageUtil.page(params);
        //TODO 查询项目组成员
        List<UserVO> userVOS = this.projectDao.selectProjectUser(params);
        Map<String, Object> res = new HashMap<>();
        //TODO 查询子项目
        Map<String, Object> subProject = this.subProjectDao.totalSize(params);
        List<SubProjectVO> subProjectVOS = this.subProjectDao.selectSubProjectList(params);
        subProject.put("subProjectList", subProjectVOS);
        res.put("userList", userVOS);
        res.put("subProject", subProject);
        return R.ok(res);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addProjectUserGroup(Map<String, Object> params) {
        //TODO获取参数
        int projectId = (int) params.get("projectId");
        List<Integer> userIds = (List<Integer>) params.get("userIds");

        //在其它项目组中没有任务
        List<UserVO> userVOS = this.projectDao.selectUserNotWorkInProject(projectId);
        List<Integer> deleteUserIds = new ArrayList<>();
        for (int i = 0; i < userIds.size(); i++) {
            uservos:
            for (UserVO userVO : userVOS) {
                if (userVO.getUserId().equals(userIds.get(i))) {
                    deleteUserIds.add(userIds.get(i));
                    break uservos;
                }
            }
        }
        if (deleteUserIds.size() > 0) {
            try {
                int i = this.projectDao.deleteUserInProject(deleteUserIds);
            } catch (Exception e) {
                e.printStackTrace();
                return R.er();
            }
        }
        //在其他项目组中任务完成度是100
        int i = this.projectDao.insertUserGroup(params);
        if (i > 0) {
            return R.ok();
        } else {
            return R.er();
        }
    }

    /**
     * 递归查询菜单
     *
     * @param moduleId
     * @param allModuleList
     * @return
     */
    public List<ModuleVO> getChildModuleList(int moduleId, List<ModuleVO> allModuleList) {
        List<ModuleVO> childModuleList = new ArrayList<>();
        for (ModuleVO moduleVO : allModuleList) {
            if (moduleVO.getParentModuleId().equals(moduleId)) {
                childModuleList.add(moduleVO);
            }
        }

        for (ModuleVO moduleVO : childModuleList) {
            List<ModuleVO> childs = getChildModuleList(moduleVO.getModuleId(), allModuleList);
            moduleVO.setChildModuleList(childs);
        }
        if (childModuleList.size() == 0) {
            return null;
        }
        return childModuleList;
    }


    /**
     * 查询项目组成员
     * params projectId
     */
    @Override
    public R selectUserOfProject(ProjectVO vo) {
        List<UserVO> userVOS = this.projectDao.selectUserOfProject(vo);
        return R.ok(userVOS);
    }

    @Override
    public R updateProject(ProjectVO vo) {
        if (vo.getProjectName() == null && vo.getTimeLimit() == null && vo.getStartTime() == null && vo.getEndTime() == null && vo.getManagerId() == null) {
            return R.er();
        }
        int row = this.projectDao.updateProject(vo);
        return row > 0 ? R.ok() : R.er();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R delProject(ProjectVO vo) {
        //删除项目
        LambdaUpdateWrapper<ProjectVO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(ProjectVO::getDelflag, "1").eq(ProjectVO::getProjectId, vo.getProjectId());
        int row = this.projectDao.update(lambdaUpdateWrapper);
        System.out.println("删除项目row-->" + row);
        //删除子项目
        this.subProjectDao.delSubProjectWithProjectId(vo.getProjectId());
        System.out.println("删除子项目row-->" + row);
        //删除任务
        this.taskDao.delTaskWithSubProjectId(vo.getProjectId());
        System.out.println("删除任务row-->" + row);
        return row > 0 ? R.ok() : R.er();
    }

}
